import React, { useState, useContext, useEffect, useCallback, useMemo } from 'react';
import { connect } from 'dva';
import {
  Spin,
  Card,
  Table,
  Button,
  Form,
  Modal,
  Input,
  Radio,
  message,
  Icon,
  Divider,
  Popconfirm,
  List,
  Pagination,
  Select,
} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import MyPageTable from '@/components/MyPageTable';
import { onTableData } from '@/utils/utils.js';
import styles from './index.less';
const { Option } = Select;
let ModalList = connect(({ coupons, loading }) => ({
  ...coupons,
  loading: loading.models.coupons,
}))(
  Form.create()(props => {
    const [KeysId, setKeysId] = useState('');
    const [InputChangs, setInputChangs] = useState('');
    useEffect(() => {
      setInputChangs('');
    }, []);
    const onSelectChange = (selectedRowKeys, is) => {
      let Id = [];
      for (let i = 0; i < is.length; i++) {
        Id.push(is[i].id);
      }
      setKeysId(Id.toString());
    };
    const InputChang = e => {
      setInputChangs(e.target.value);
    };
    const onSsTable = () => {
      props.dispatch({
        type: 'coupons/getAssignAbleTemplate',
        payload: {
          title: InputChangs,
          pageNumber: 1,
          pageSize: 100,
          //forPackage: 'T',
          //status: 'UNASSIGNED',
          //type: "PACKAGE",
          //status: "VALID",
          //hasAssign: false,
          // sourceShopId: getShopId()
        },
      });
    };
    const onThepage = e => {
      props.dispatch({
        type: 'coupons/getAssignAbleTemplate',
        payload: {
          title: InputChangs,
          pageNumber: e.current,
          pageSize: 100,
          // forPackage: 'T',
          // status: 'UNASSIGNED',
          // type: "PACKAGE",
          // status: "VALID",
          // hasAssign: false,
          // sourceShopId: getShopId()
        },
      });
    };
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
        md: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 17 },
        md: { span: 17 },
      },
    };
    const { getFieldDecorator, validateFields } = props.form;
    const RadioGroup = Radio.Group;

    const okHandle = e => {
      e.preventDefault();
      validateFields((err, values) => {
        if (!err) {
          if (props.control) {
            props.dispatch({
              type: 'coupons/couponPackagemodify',
              payload: {
                id: props.Data.id,
                ...values,
                templateIds: props.Data.templateIds,
              },
              callback: res => {
                message.success('编辑大礼包成功');
                props.onCancel();
                props.handleSubmit();
                // props.couponPackageList();
              },
            });
          } else {
            if (KeysId === '') {
              message.error('请选择优惠券～');
            } else {
              props.dispatch({
                type: 'coupons/couponPackage',
                payload: {
                  ...values,
                  // sourceShopId: getShopId(),
                  templateIds: KeysId,
                },
                callback: res => {
                  message.success('新增大礼包成功');
                  props.onCancel();
                  props.handleSubmit();
                  // props.couponPackageList();
                },
              });
            }
          }
        }
      });
    };
    const columns = [
      {
        title: '优惠券ID',
        dataIndex: 'id',
      },
      {
        title: '名称',
        dataIndex: 'title',
      },
      {
        title: '发放总量',
        dataIndex: 'num',
      },
      {
        title: '库存',
        dataIndex: 'leftNum',
      },
      {
        title: '面额',
        dataIndex: 'discountAmount',
      },
    ];
    return (
      <Modal
        title={props.titls}
        visible={props.visible}
        onCancel={props.onCancel}
        style={{ minWidth: 1025 }}
        destroyOnClose={true}
        onOk={okHandle}
      >
        <Spin spinning={false}>
          <Form>
            <Form.Item {...formItemLayout} label="用法" required>
              {getFieldDecorator('type', {
                rules: [{ required: true, message: '请选择' }],
                initialValue: 'SINGLE',
              })(
                <Select>
                  <Option value="SINGLE">独立使用</Option>
                  <Option value="ACTIVITY">营销活动</Option>
                </Select>,
              )}
            </Form.Item>
            <Form.Item {...formItemLayout} label="大礼包名称" required>
              {getFieldDecorator('name', {
                rules: [{ required: true, message: '请输入大礼包名称' }],
                initialValue: props.Data.name,
              })(<Input placeholder="请输入大礼包名称" />)}
            </Form.Item>
            <Form.Item {...formItemLayout} label="数量" required>
              {getFieldDecorator('num', {
                rules: [{ required: true, message: '请输入' }],
                initialValue: props.Data.num,
              })(<Input placeholder="请输入" />)}
            </Form.Item>
            <Form.Item {...formItemLayout} label="每人限领" required>
              {getFieldDecorator('userLimitNum', {
                rules: [{ required: true, message: '请输入' }],
                initialValue: props.Data.userLimitNum,
              })(<Input placeholder="请输入" />)}
            </Form.Item>
            <Form.Item {...formItemLayout} label="新用户专享" required>
              {getFieldDecorator('forNew', {
                rules: [{ required: true, message: '请选择' }],

                initialValue: props.Data.forNew || 'T',
              })(
                <RadioGroup disabled={props.control}>
                  <Radio value="T">是</Radio>
                  <Radio value="F">否</Radio>
                </RadioGroup>,
              )}
            </Form.Item>
            <Form.Item {...formItemLayout} label="大礼包状态" required>
              {getFieldDecorator('status', {
                rules: [{ required: true, message: '请选择' }],
                initialValue: props.Data.status || 'VALID',
              })(
                <RadioGroup>
                  <Radio value="VALID">有效</Radio>
                  <Radio value="INVALID">失效</Radio>
                </RadioGroup>,
              )}
            </Form.Item>
          </Form>
          {!props.control ? (
            <Form.Item {...formItemLayout} label="添加优惠券">
              <div
                style={{
                  display: 'flex',
                }}
              >
                <Input
                  placeholder="请输入优惠券名称"
                  style={{ width: 200, marginRight: 30 }}
                  onChange={InputChang}
                />
                <Button onClick={onSsTable} type="primary">
                  查询
                </Button>
              </div>
            </Form.Item>
          ) : null}
          <Table
            columns={columns}
            dataSource={props.control ? props.Data.couponTemplateList : props.listData2}
            size="middle"
            rowKey={record => record.id}
            pagination={{
              current: 1,
              pageSize: 10,
            }}
            onChange={onThepage}
            rowSelection={
              props.control
                ? null
                : {
                    onChange: onSelectChange,
                  }
            }
          />
        </Spin>
      </Modal>
    );
  }),
);

let Package = Form.create()(props => {
  const [visibles, setvisibles] = useState(false);
  const [tableData, setTableData] = useState([]);
  const [data, setData] = useState({});
  const [control, setcontrol] = useState(false);
  const [titls, settitls] = useState('新增大礼包');
  const [TotleData, setTotleData] = useState(1);
  const [pageNumbers, setpageNumbers] = useState(1);
  const [templateIdss, settemplateIdss] = useState('');
  useEffect(() => {
    couponPackageList({
      status: "VALID",
      type: "SINGLE",
    });
  }, []);
  const couponPackageList = (data = {}) => {
    props.dispatch({
      type: 'coupons/couponPackageList',
      payload: {
        // sourceShopId: getShopId(),
        pageNumber: 1,
        pageSize: 10,
        ...data,
        type: data.type ? data.type : ''
      },
      callback: res => {
        const data = res.data.records || [];
        const tableData = [];
        data.map(item => {
          if (item.couponTemplateList && item.couponTemplateList.length) {
            item.couponTemplateList.map((item2, index2) => {
              for (let key in item2) {
                item2[`couponTemplateList_${key}`] = item2[key];
                delete item2[key];
              }
              
              tableData.push({
                rowSpan: index2 === 0 ? item.couponTemplateList.length : 0,
                ...item,
                ...item2,
              });
            });
          } else {
            tableData.push({
              rowSpan: 1,
              ...item,
            });
          }
        });

        setTableData(tableData);
        setTotleData(res.data.total);
      },
    });
  };
  // 重置
  const handleReset = e => {
    props.form.resetFields();
    props.form.setFieldsValue({
      status: undefined,
      type: undefined,
    });
    handleSubmit(e);
  };
  const onPagination = e => {
    props.form.validateFields((err, values) => {
      if (!err) {
        props.dispatch({
          type: 'coupons/couponPackageList',
          payload: {
            // sourceShopId: getShopId(),
            pageNumber: e.current,
            pageSize: 10,
            status: 'VALID',
            type: 'SINGLE',
            ...values,
          },
          callback: res => {
            const data = res.data.records || [];
            const tableData = [];
            data.map(item => {
              if (item.couponTemplateList && item.couponTemplateList.length) {
                item.couponTemplateList.map((item2, index2) => {
                  for (let key in item2) {
                    item2[`couponTemplateList_${key}`] = item2[key];
                    delete item2[key];
                  }
    
                  tableData.push({
                    rowSpan: index2 === 0 ? item.couponTemplateList.length : 0,
                    ...item,
                    ...item2,
                  });
                });
              } else {
                tableData.push({
                  rowSpan: 1,
                  ...item,
                });
              }
            });
    
            setpageNumbers(e.current);
            setTableData(tableData);
            setTotleData(res.data.total);
          },
        });
      }
    })
  };
  const onCancels = () => {
    setvisibles(false);
  };
  const onModalList = () => {
    setcontrol(false);
    setData({});
    setvisibles(true);
    settitls('新增大礼包');
  };
  const handleDelete = id => {
    props.dispatch({
      type: 'coupons/couponPackageDelete',
      payload: {
        id: id,
      },
      callback: res => {
        message.success('删除成功！～');
        handleSubmit();
        // couponPackageList();
      },
    });
  };
  const onTheEditor = id => {
    console.log(id, 'id');
    // debugger;
    props.dispatch({
      type: 'coupons/getPageData',
      payload: {
        id: id,
      },
      callback: res => {
        onModalList();
        setData(res.data);
        settitls('编辑大礼包');
        setcontrol(true);
      },
    });
  };
  const handleSubmit = e => {
    e && e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        couponPackageList(values);
      }
    });
  };

  const paginationProps = {
    current: pageNumbers,
    pageSize: 10,
    total: TotleData,
    showTotal: total => (
      <span style={{ fontSize: '14px' }}>
        <span>共{Math.ceil(total / 10)}页</span>&emsp;
        <span>共{total}条</span>
      </span>
    ),
  };
  const columnsData = [
    {
      title: '大礼包ID',
      dataIndex: 'id',
      render: (text, e) => {
        return {
          children: e.id,
          props: {
            rowSpan: e.rowSpan
          },
        };
      },
    },
    {
      title: '大礼包名称',
      dataIndex: 'name',
      render: (text, e) => {
        return {
          children: e.name,
          props: {
            rowSpan: e.rowSpan
          },
        };
      },
    },
    {
      title: '新用户专享',
      render: (text, e) => {
        return {
          children: (e.forNew === 'T' ? '是' : '否'),
          props: {
            rowSpan: e.rowSpan
          },
        };
      },
    },
    {
      title: '大礼包状态',
      render: (text, e) => {
        return {
          children: (e.status === 'VALID' ? '有效' : '无效'),
          props: {
            rowSpan: e.rowSpan
          },
        };
      },
    },
    {
      title: '优惠券名称',
      render: (text, e) => {
        return {
          children: e.couponTemplateList_title,
          props: {
            rowSpan: 1
          },
        };
      },
    },
    {
      title: '发放总量',
      render: (text, e) => {
        return {
          children: e.couponTemplateList_num,
          props: {
            rowSpan: 1
          },
        };
      },
    },
    {
      title: '库存',
      render: (text, e) => {
        return {
          children: e.couponTemplateList_leftNum,
          props: {
            rowSpan: 1
          },
        };
      },
    },
    {
      title: '面额',
      render: (text, e) => {
        return {
          children: e.couponTemplateList_discountAmount,
          props: {
            rowSpan: 1
          },
        };
      },
    },
    {
      title: '使用条件',
      render: (text, e) => {
        return {
          children: e.couponTemplateList_minAmount === 0 ? '不限制' : `满${e.couponTemplateList_minAmount}元使用`,
          props: {
            rowSpan: 1
          },
        };
      },
    },
    {
      title: '每人限领',
      render: (text, e) => {
        return {
          children: e.couponTemplateList_userLimitNum === 0 ? '不限' : `${e.couponTemplateList_userLimitNum}张`,
          props: {
            rowSpan: 1
          },
        };
      },
    },
    {
      title: '时间设置',
      render: (text, e) => {
        return {
          children: (
            <div>
              {e.couponTemplateList_delayDayNum ? (
                `自领取${e.couponTemplateList_delayDayNum}天内使用`
              ) : (
                <div>
                  <div>开始：{e.couponTemplateList_startTime}</div>
                  <div>结束：{e.couponTemplateList_endTime}</div>
                </div>
              )}
            </div>
          ),
          props: {
            rowSpan: 1
          },
        };
      },
    },
    {
      title: '操作',
      width: '100px',
      render: (text, e) => {
        return {
          children: (
            <div>
              <div>
                <a>
                  <span onClick={() => onTheEditor(e.id)}>修改</span>
                </a>
              </div>

              <Popconfirm title="是否删除该大礼包优惠券？" onConfirm={() => handleDelete(e.id)}>
                <a>
                  <span>删除</span>
                </a>
              </Popconfirm>
            </div>
          ),
          props: {
            rowSpan: e.rowSpan
          },
        };
      },
    },
  ];
  const { getFieldDecorator, validateFields } = props.form;
  console.log('tableData:', tableData);
  return (
    <PageHeaderWrapper title="大礼包">
      <Spin spinning={false}>
        <Card bordered={false}>
          <Form layout="inline" onSubmit={handleSubmit}>
            <Form.Item label={'用法'}>
              {getFieldDecorator(
                'type',
                {
                  initialValue: 'SINGLE',
                },
              )(
                <Select placeholder="用法" style={{ width: 180 }}>
                  <Option value="SINGLE">独立使用</Option>
                  <Option value="ACTIVITY">营销活动</Option>
                </Select>,
              )}
            </Form.Item>
            <Form.Item label={'大礼包名称'}>
              {getFieldDecorator('name', {})(<Input placeholder="请输入大礼包名称" />)}
            </Form.Item>
            <Form.Item label={'大礼包状态'}>
              {getFieldDecorator(
                'status',
                {
                  initialValue: 'VALID',
                },
              )(
                <Select placeholder="大礼包状态" allowClear style={{ width: 180 }}>
                  <Option value="VALID">有效</Option>
                  <Option value="INVALID">失效</Option>
                </Select>,
              )}
            </Form.Item>
            <div>
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
              </Form.Item>
              <Form.Item>
                <Button htmlType="button" onClick={handleReset}>
                  重置
                </Button>
              </Form.Item>
              {/* <Form.Item>
                <Button>导出</Button>
              </Form.Item> */}
            </div>
          </Form>
          <Button
            onClick={onModalList}
            type="primary"
            // shape="round"
            style={{ margin: '30px 0' }}
          >
            新增
          </Button>
          <MyPageTable
            onPage={onPagination}
            paginationProps={paginationProps}
            dataSource={onTableData(tableData)}
            columns={columnsData}
          />
        </Card>

        <ModalList
          visible={visibles}
          onCancel={onCancels}
          couponPackageList={couponPackageList}
          Data={data}
          handleSubmit={handleSubmit}
          control={control}
          titls={titls}
        />
      </Spin>
    </PageHeaderWrapper>
  );
});

export default connect(({}) => ({}))(Package);
